package com.example.itas;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import com.example.classes.IP;
import com.example.classes.Pcroomlist;
import com.example.classes.Seat;
import com.example.scroll.HScroll;
import com.example.scroll.VScroll;
import com.google.android.gms.maps.GoogleMap.OnInfoWindowClickListener;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.Toast;

public class ReservationActivity extends Activity {

	public static final int NONE = 0;
	public static final int DRAG = 5;
	IP ip = new IP();
	private final String HOST = ip.ip;
	private final int PORT = 8080;
	private final String PATH = "/IServer-war/webresources/entities.pcroomlist/getPcroom";
	private final String TAG = "ReservationActivity";

	private int touchMode;
	private float mx, my;
	private float clickX, clickY;
	private VScroll vScroll;
	private HScroll hScroll;
	private PcroomBackgroundView seatBackground;
	private Bitmap seatBackImage;
	private Button seatReservationButton;
	private long id;
	
	private ArrayList<Integer> resSeat;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_reservation);

		Intent intent = this.getIntent();
		id = intent.getLongExtra("ID", -1);

//		GetSeats gs = new GetSeats();
//		gs.execute();
		
		AsyncGet ag = new AsyncGet();
		ag.execute();

		vScroll = (VScroll) findViewById(R.id.vscroll);
		hScroll = (HScroll) findViewById(R.id.hscroll);
		seatBackground = (PcroomBackgroundView) findViewById(R.id.seat_background);
		seatReservationButton = (Button) findViewById(R.id.reservation_button);
		
		resSeat = new ArrayList<Integer>();
		seatBackImage = Bitmap.createBitmap(2000, 2000, Config.ARGB_8888);
		seatBackground.setImageBitmap(seatBackImage);
		touchMode = NONE;

		seatReservationButton.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				
				Intent intent = new Intent();
				intent.putIntegerArrayListExtra("X", resSeat);
				setResult(1, intent);
				finish();
			}
		});
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		float curX, curY;
		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:
			mx = event.getX();
			my = event.getY();
			touchMode = NONE;
			break;
		case MotionEvent.ACTION_MOVE:
			curX = event.getX();
			curY = event.getY();
			vScroll.scrollBy((int) (mx - curX), (int) (my - curY));
			hScroll.scrollBy((int) (mx - curX), (int) (my - curY));
			mx = curX;
			my = curY;
			touchMode++;
			break;
		case MotionEvent.ACTION_UP:
			curX = event.getX();
			curY = event.getY();
			vScroll.scrollBy((int) (mx - curX), (int) (my - curY));
			hScroll.scrollBy((int) (mx - curX), (int) (my - curY));
			if (touchMode >= DRAG)
				touchMode = NONE;
			else if (touchMode < DRAG) {
				ArrayList<Integer> seatX = seatBackground.getSetSeatW();
				ArrayList<Integer> seatY = seatBackground.getSetSeatH();
				ArrayList<Integer> seatNum = seatBackground.getSeatNum();
				ArrayList<Integer> seatMode = seatBackground.getSeatMode();
				clickX = hScroll.getScrollX() + mx;
				clickY = vScroll.getScrollY() + my;
				Log.i(TAG,
						clickX + " " + clickY + " "
								+ seatBackground.getSeatImageW());
				for (int i = 0; i < seatX.size(); ++i) {
					if (seatX.get(i) * seatBackground.getSeatImageW() <= clickX
							&& clickX <= (seatX.get(i) + 1)
									* seatBackground.getSeatImageW()
							&& seatY.get(i) * seatBackground.getSeatImageH() <= clickY
							&& clickY <= (seatY.get(i) + 1)
									* seatBackground.getSeatImageH()) {
						
						switch(seatMode.get(i))
						{
						case PcroomBackgroundView.PC_AVAILABLE:
							seatBackground.setSeat(seatNum.get(i), PcroomBackgroundView.PC_SELECTED);
							resSeat.add(seatNum.get(i));
							break;
						case PcroomBackgroundView.PC_SELECTED:
							seatBackground.setSeat(seatNum.get(i), PcroomBackgroundView.PC_AVAILABLE);
							for(int j = 0; j < resSeat.size(); j++)
							{
								if(resSeat.get(j)==seatNum.get(i))
								{
									resSeat.remove(j);
									break;
								}
							}
							break;
						}
						//Intent intent = new Intent();
						//intent.putExtra("X", seatNum.get(i));
						//setResult(1, intent);
					}
				}
			}
			break;
		}
		// Log.i(TAG, "mx = "+hScroll.getScrollX()+" "+hScroll.getWidth()+" "+mx
		// + " my = " +vScroll.getScrollY()+" "+ vScroll.getHeight()+" "+ my);
		return true;
	}

	// private class GetSeats extends AsyncTask<Void, Void, Pcroomlist> {
	//
	// @Override
	// protected void onPreExecute() {
	// // TODO Auto-generated method stub
	// super.onPreExecute();
	// }
	//
	// @Override
	// protected Pcroomlist doInBackground(Void... params) {
	// HttpHost target = new HttpHost(HOST, PORT);
	// HttpClient client = new DefaultHttpClient();
	// HttpPost post = new HttpPost(PATH);
	//
	// post.setHeader("Content-Type", "application/json");
	// // String str = StringtoJSON(UseApp.getRoomid()+"");
	//
	// HttpEntity entity = null;
	// StringEntity se;
	//
	// try {
	// se = new StringEntity(id+"", HTTP.UTF_8);
	// post.setEntity(se);
	//
	// HttpResponse response = client.execute(target, post);
	//
	// Log.d(TAG, id + "");
	// Log.d(TAG, "" + response.getStatusLine().getStatusCode());
	// if (response.getStatusLine().getStatusCode() != 200)
	// return null;
	//
	// entity = response.getEntity();
	// String str = EntityUtils.toString(entity, "utf-8");
	// Log.d(TAG, str);
	// // ArrayList<Seat> s = JSONtoSeat(str);
	// Pcroomlist p = JSONtoPcroom(str);
	// return p;
	// } catch (UnsupportedEncodingException e) {
	// e.printStackTrace();
	// } catch (ClientProtocolException e) {
	// e.printStackTrace();
	// } catch (IOException e) {
	// e.printStackTrace();
	// }
	// return null;
	// }
	//
	// @Override
	// protected void onPostExecute(Pcroomlist result) {
	// if (result != null) {
	// Toast.makeText(getApplicationContext(),
	// "Success to get buildings!", Toast.LENGTH_SHORT).show();
	// // for (Seat s : result) {
	// // if (s.getNum() != 0)
	// // seatBackground.setSeat(s.getX(), s.getY());
	// // }
	// } else {
	// Toast.makeText(getApplicationContext(),
	// "Fail to get PC Rooms!", Toast.LENGTH_SHORT).show();
	// }
	// }
	// }
	// private Pcroomlist JSONtoPcroom(String json) {
	// Gson gson = new Gson();
	// Type t = new TypeToken<Pcroomlist>() {
	// }.getType();
	// Pcroomlist p = gson.fromJson(json, t);
	// return p;
	// }
	// // private ArrayList<Seat> JSONtoSeat(String json) {
	// // Gson gson = new Gson();
	// // Type t = new TypeToken<ArrayList<Seat>>() {
	// // }.getType();
	// // ArrayList<Seat> s = gson.fromJson(json, t);
	// // return s;
	// // }
	private class AsyncGet extends AsyncTask<Void, Void, List<Pcroomlist>> {

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
		}

		@Override
		protected List<Pcroomlist> doInBackground(Void... params) {
			HttpHost target = new HttpHost(HOST, PORT);
			HttpClient client = new DefaultHttpClient();
			HttpGet get = new HttpGet(PATH);

			// set the MIME type for POST message body.
			get.setHeader("Content-Type", "application/json");

			HttpEntity entity = null;
			try {
				HttpResponse response = client.execute(target, get);
				Log.d(TAG, "" + response.getStatusLine().getStatusCode());
				if (response.getStatusLine().getStatusCode() != 200)
					return null;

				entity = response.getEntity();
				String str = EntityUtils.toString(entity, "utf-8");
				Log.d(TAG, str);
				List<Pcroomlist> p = JSONtoPcroom(str);
				return p;
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(List<Pcroomlist> result) {
			if (result != null) {
				Toast.makeText(getApplicationContext(),
						"Success to get buildings!", Toast.LENGTH_SHORT).show();
				for (Pcroomlist p : result) {
					if (p.getId() == id) {
						for (Seat s : p.getSeats()) {
							if (s.getNum() != 0)
								if(true)//s.getInfo().getIsAvailable())
									seatBackground.setSeat(s.getX(), s.getY(), s.getNum(), PcroomBackgroundView.PC_AVAILABLE);
								else
									seatBackground.setSeat(s.getX(), s.getY(), s.getNum(), PcroomBackgroundView.PC_NOT_AVAILABLE);
						}

					}
				}
			} else {
				Toast.makeText(getApplicationContext(),
						"Fail to get PC Rooms!", Toast.LENGTH_SHORT).show();
			}
		}
	}

	private List<Pcroomlist> JSONtoPcroom(String json) {
		Gson gson = new Gson();
		Type t = new TypeToken<List<Pcroomlist>>() {
		}.getType();
		List<Pcroomlist> p = gson.fromJson(json, t);
		return p;
	}

}
